<template xmlns="http://www.w3.org/1999/html">
  <div class="progress-container w-full p-8 bg-white rounded-lg shadow-md">
      <span class="text-3xl font-bold mb-6 text-gray-800">任务进度跟踪</span>
    <el-divider />
<!--    <el-button size=small v-hasPermi="['operation:busisystem:concurrent']" @click="()=>{console.log('同步')}">同步cmdb数据</el-button>-->
<!--    <el-divider />-->
    <div class="mb-4">
      <div class="flex justify-between mb-2">
        <span class="text-sm font-medium text-gray-700">当前进度</span>
        <div class="flex gap-4">
          <span class="text-sm font-medium text-black-600">总任务数:{{allChildTasks.length}}条</span>
          <span class="text-sm font-medium text-green-600"
            >已完成: {{ completedPercentage }}%</span
          >
          <span class="text-sm font-medium text-blue-600"
            >进行中: {{ inProgressPercentage }}%</span
          >
          <span class="text-sm font-medium text-gray-600"
            >未开始: {{ 100 - completedPercentage - inProgressPercentage
            }}%</span
          >
        </div>
      </div>
      <div class="relative h-6 bg-gray-200 rounded-full overflow-hidden w-full">
        <!-- 已完成部分 -->
        <div
          class="absolute left-0 top-0 h-full bg-green-500 cursor-pointer transition-all duration-300"
          :style="{ width: `${completedPercentage}%` }"
          @click="handleProgressClick('completed')"
          @mouseenter="showCompletedTooltip = true"
          @mouseleave="showCompletedTooltip = false"
          ref="completedBarRef"
        ></div>
        <!-- 进行中部分 -->
        <div
          class="absolute top-0 h-full cursor-pointer transition-all duration-300 bg-blue-500"
          :style="{ width: `${inProgressPercentage}%`, left: `${completedPercentage}%` }"
          @click="handleProgressClick('inProgress')"
          @mouseenter="showInProgressTooltip = true"
          @mouseleave="showInProgressTooltip = false"
          ref="inProgressBarRef"
        ></div>
        <!-- 未完成部分 -->
        <div
          class="absolute top-0 h-full right-0 cursor-pointer transition-all duration-300"
          :style="{ width: `${100 - completedPercentage - inProgressPercentage}%`, left: `${completedPercentage + inProgressPercentage}%` }"
          @click="handleProgressClick('incomplete')"
          @mouseenter="showIncompleteTooltip = true"
          @mouseleave="showIncompleteTooltip = false"
          ref="incompleteBarRef"
        ></div>
        <!-- 已完成提示框 -->
        <el-popover
          :visible="showCompletedTooltip"
          placement="top"
          :width="300"
          trigger="manual"
          popper-class="custom-popover"
          :reference="completedBarRef"
        >
          <template #default>
            <div class="p-2">
              <h3 class="text-base font-bold text-gray-800 mb-2">
                已完成项目 ({{ allCompletedTasks.length }})
              </h3>
              <ul class="max-h-60 overflow-y-auto">
                <li
                  v-for="(task, index) in allCompletedTasks"
                  :key="`completed-${index}`"
                  class="py-2 border-b border-gray-100 last:border-0 flex items-start"
                >
                  <el-icon class="mr-2 text-green-500"><Check /></el-icon>
                  <span>{{ task.name }}</span>
                </li>
              </ul>
            </div>
          </template>
        </el-popover>
        <!-- 未完成提示框 -->
        <el-popover
          :visible="showIncompleteTooltip"
          placement="top"
          :width="300"
          trigger="manual"
          popper-class="custom-popover"
          :reference="incompleteBarRef"
        >
          <template #default>
            <div class="p-2">
              <h3 class="text-base font-bold text-gray-800 mb-2">
                未完成项目 ({{ allIncompleteTasks.length }})
              </h3>
              <ul class="max-h-60 overflow-y-auto">
                <li
                  v-for="(task, index) in allIncompleteTasks"
                  :key="`incomplete-${index}`"
                  class="py-2 border-b border-gray-100 last:border-0 flex items-start"
                >
                  <el-icon class="mr-2 text-gray-400"><Clock /></el-icon>
                  <span>{{ task.name }}</span>
                </li>
              </ul>
            </div>
          </template>
        </el-popover>
      </div>
    </div>
    <el-dialog
      v-model="showTaskDialog"
      :title="dialogTitle"
      width="50%"
      class="task-dialog"
    >
      <el-tree
        :data="currentTreeData"
        :props="defaultProps"
        :expand-on-click-node="false"
        node-key="id"
        default-expand-all
      >
        <template #default="{ node, data }">
          <div class="flex items-center justify-between w-full">
            <div class="flex items-center">
              <el-icon
                :class="data.completed ? 'text-green-500' : 'text-gray-400'"
                class="mr-2"
              >
                <component :is="data.completed ? Check : Clock" />
              </el-icon>
              <span>{{ data.label }}</span>
            </div>
            <div class="text-sm text-gray-500">
              预计完成时间: {{ data.dueDate }}
            </div>
          </div>
        </template>
      </el-tree>
    </el-dialog>
    <div class="mt-8 text-center text-sm text-gray-500">
      最后更新时间: {{ currentDate }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Check, Clock } from "@element-plus/icons-vue";
import { tree } from "@/api/operation/gentask";

// 任务数据
const tasks = ref([]);

// 获取所有子任务（平铺结构）
const allChildTasks = computed(() => {
  return tasks.value.flatMap(task =>
    task.children ? task.children : []
  );
});

// 计算各状态的所有子任务
const allCompletedTasks = computed(() =>
  allChildTasks.value.filter((task) => task.status === "completed")
);
const allInProgressTasks = computed(() =>
  allChildTasks.value.filter((task) => task.status === "inProgress")
);
const allIncompleteTasks = computed(() =>
  allChildTasks.value.filter((task) => task.status === "incomplete")
);

// 计算各状态的百分比（基于所有子任务）
const completedPercentage = computed(() => {
  const total = allChildTasks.value.length;
  return total > 0 ? Math.round((allCompletedTasks.value.length / total) * 100) : 0;
});

const inProgressPercentage = computed(() => {
  const total = allChildTasks.value.length;
  return total > 0 ? Math.round((allInProgressTasks.value.length / total) * 100) : 0;
});

// 提示框显示状态
const showCompletedTooltip = ref(false);
const showIncompleteTooltip = ref(false);
const showInProgressTooltip = ref(false);

// 进度条引用
const completedBarRef = ref(null);
const incompleteBarRef = ref(null);
const inProgressBarRef = ref(null);

// 对话框相关
const showTaskDialog = ref(false);
const dialogTitle = ref("");
const currentTreeData = ref([]);
const defaultProps = {
  children: "children",
  label: "name",
};

// 处理进度条点击
const handleProgressClick = (type) => {
  showTaskDialog.value = true;
  dialogTitle.value =
    type === "completed"
      ? "已完成任务"
      : type === "inProgress"
        ? "进行中任务"
        : "未开始任务";

  // 转换任务数据为树形结构，只显示匹配状态的子任务
  const filteredTasks = tasks.value
    .map((task) => {
      const hasMatchingChildren = task.children && task.children.some(child =>
        (type === "completed" && child.status === "completed") ||
        (type === "inProgress" && child.status === "inProgress") ||
        (type === "incomplete" && child.status === "incomplete")
      );

      if (hasMatchingChildren) {
        return {
          id: task.id,
          label: task.name,
          completed: false,
          dueDate: '',
          children: task.children.filter(child => {
            return (
              (type === "completed" && child.status === "completed") ||
              (type === "inProgress" && child.status === "inProgress") ||
              (type === "incomplete" && child.status === "incomplete")
            );
          }).map(child => ({
            id: child.id,
            label: child.name,
            completed: child.status === "completed",
            dueDate: child.dueDate || '',
          }))
        };
      }
      return null;
    })
    .filter(Boolean);

  currentTreeData.value = filteredTasks;
};

// 日期格式化函数
const getFormattedDateTime = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  const hours = String(today.getHours()).padStart(2, '0');
  const minutes = String(today.getMinutes()).padStart(2, '0');
  const seconds = String(today.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const currentDate = ref(getFormattedDateTime());

const getCurrentDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}${month}${day}`;
};

// 从接口获取任务数据
const fetchTasks = async () => {
  try {
    const date = getCurrentDate();
    const response = await tree(date);
    console.log(response, "=====")
    tasks.value = response.data || [];
  } catch (error) {
    console.error('获取任务数据失败:', error);
    tasks.value = [];
  }
};

onMounted(() => {
  fetchTasks();
});
</script>
<style scoped>
.header{
  //margin-bottom: 20px;
}
.task-list::-webkit-scrollbar {
  width: 6px;
}
.task-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}
.task-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}
.task-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
/* 确保弹出框内容可滚动 */
.custom-popover ul::-webkit-scrollbar {
  width: 6px;
}
.custom-popover ul::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}
.custom-popover ul::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}
.custom-popover ul::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
:deep(.el-tree-node__content) {
  height: 40px;
}
:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style>
